package com.whccb.apps.office.document.util;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import org.apache.commons.lang.StringUtils;

import com.actionsoft.bpms.bo.engine.BO;
import com.actionsoft.bpms.commons.formfile.model.delegate.FormFile;
import com.actionsoft.bpms.commons.mvc.view.ResponseObject;
import com.actionsoft.bpms.org.cache.DepartmentCache;
import com.actionsoft.bpms.org.cache.UserCache;
import com.actionsoft.bpms.org.cache.UserMapCache;
import com.actionsoft.bpms.org.model.DepartmentModel;
import com.actionsoft.bpms.org.model.UserMapModel;
import com.actionsoft.bpms.org.model.UserModel;
import com.actionsoft.bpms.server.UserContext;
import com.actionsoft.bpms.server.fs.DCContext;
import com.actionsoft.sdk.local.SDK;
import com.whccb.apps.office.document.ODConstant;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

public class ODAppUtil {

    public static String getODParamValue(String param) {
        String value = SDK.getAppAPI().getProperty(ODConstant.APP_ID, param);
        if (value == null) {
            return "";
        } else {
            return value;
        }
    }

    public static String getAppParamValue(String appId, String param) {
        String value = SDK.getAppAPI().getProperty(appId, param);
        if (value == null) {
            return "";
        } else {
            return value;
        }
    }

    public static FormFile getSingleFormFile(String boName, String fieldName,
            String bindid) {
        FormFile formFile = null;
        if (StringUtils.isNotEmpty(boName) && StringUtils.isNotEmpty(fieldName)
                && StringUtils.isNotEmpty(bindid)) {
            List<FormFile> formFiles = null;
            try {
                formFiles = SDK.getBOAPI().getFiles(
                        SDK.getBOAPI().getByProcess(boName, bindid).getId(),
                        fieldName);
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (formFiles != null && !formFiles.isEmpty()
                    && formFiles.size() > 0) {
                for (FormFile thisFormFile : formFiles) {
                    if (thisFormFile != null) {
                        formFile = thisFormFile;
                        break;
                    }
                }
            }
        }
        return formFile;
    }

    public static String getUserDeptSqlInWhere(String result, String deptId) {
        if (StringUtils.isEmpty(result)) {
            result = "('',";
        }
        DepartmentModel depart = DepartmentCache.getModel(deptId);
        if (depart != null) {
            result = result + "'" + depart.getId() + "',";
            return getUserDeptSqlInWhere(result,
                    depart.getParentDepartmentId());
        } else {
            result = result.substring(0, result.lastIndexOf(",")) + ")";
            return result;
        }
    }

    public static Map<String, Object> getRedHeaderFileParam(UserContext user,
            String recordTypeId) {
        Map<String, Object> macroLibraries = new HashMap<String, Object>();
        JSONObject templateDataJson = new JSONObject();
        JSONObject templateListJson = new JSONObject();
        JSONArray jsons = new JSONArray();
        BO recordTypeBo = SDK.getBOAPI().get("BO_WHBK_OD_RECORDTYPE",
                recordTypeId);
        if (recordTypeBo != null) {
            List<FormFile> formFileList = SDK.getBOAPI()
                    .getFiles(recordTypeBo.getId(), "REDHEADERFILE");
            if (formFileList != null && !formFileList.isEmpty()
                    && formFileList.size() > 0) {
                FormFile formFile = formFileList.get(0);
                if (formFile != null) {
                    DCContext redHeaderFileDC = SDK.getBOAPI()
                            .getFileDCContext(formFile);
                    redHeaderFileDC.setSession(user);
                    if (redHeaderFileDC != null) {
                        JSONObject json = new JSONObject();
                        json.put("templateId", recordTypeBo.getId());
                        json.put("appId", ODConstant.APP_ID);
                        json.put("fileName",
                                recordTypeBo.getString("REDHEADERFILE"));
                        json.put("downloadUrl",
                                redHeaderFileDC.getDownloadURL());
                        json.put("repositoryName",
                                redHeaderFileDC.getRepositoryName());
                        json.put("typeId", recordTypeBo.getId());
                        jsons.add(json);
                    }
                }
            }
        }
        templateListJson.put("templateList", jsons);
        templateDataJson.put("data", templateListJson);
        macroLibraries.put("templateJson", templateDataJson);
        return macroLibraries;
    }

    public static void sendOfficeDocumentNotification(
            Map<String, Object> params) {
        ResponseObject localResponseObject = SDK.getAppAPI().callASLP(
                SDK.getAppAPI().getAppContext(ODConstant.APP_ID),
                "aslp://com.actionsoft.apps.notification/sendMessage", params);
    }

    public boolean userIsHasRole(String uid, String roleid) {
        boolean result = false;
        UserModel user = UserCache.getModel(uid);
        if (user != null && StringUtils.isNotEmpty(roleid)) {
            // 先检查主角色
            if (roleid.equals(user.getRoleId())) {
                result = true;
            } else {
                // 再检查兼职角色
                List<UserMapModel> userMapList = UserMapCache
                        .getMapListOfUser(uid);
                if (userMapList != null && !userMapList.isEmpty()
                        && userMapList.size() > 0) {
                    for (UserMapModel userMap : userMapList) {
                        if (userMap != null
                                && roleid.equals(userMap.getRoleId())) {
                            result = true;
                            break;
                        }
                    }
                }
            }
        }
        return result;
    }

    public static Properties getProperties(String propertiesName) {
        Properties dbProps = new Properties();
        InputStream inputStream = null;
        try {
            ClassLoader cl = SDK.getAppAPI().getAppContext(ODConstant.APP_ID)
                    .getBindClassLoader();
            if (cl != null) {
                inputStream = cl.getResourceAsStream(propertiesName);
            } else {
                inputStream = ClassLoader
                        .getSystemResourceAsStream(propertiesName);
            }
            dbProps = new Properties();
            dbProps.load(inputStream);
        } catch (Exception exception) {
            exception.printStackTrace();
        } finally {
            try {
                inputStream.close();
            } catch (IOException exception) {
                exception.printStackTrace();
            }
        }
        return dbProps;
    }

}
